package org.jawa.dao.hibernate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.sql.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jawa.dao.ProductDao;
import org.jawa.model.Product;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ProductDaoHibernate extends HibernateDaoSupport implements
		ProductDao {
	Log log=LogFactory.getLog(ProductDaoHibernate.class);
	
	@Override
	public void delete(Long productID) {
		// TODO Auto-generated method stub
		getHibernateTemplate().delete(getProduct(productID));
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getAll() {
		// TODO Auto-generated method stub
		List<Product> list=getHibernateTemplate().find("from Product order by id");
		if(list.isEmpty()){
			return null;
		}else{
			return list;
		}
	}

	@Override
	public Product getProduct(Long productID) {
		// TODO Auto-generated method stub
		Product product=(Product)getHibernateTemplate().load(Product.class, productID);
		if(null==product){
			log.debug("Sorry this id of Product is not exist!");
			throw new ObjectRetrievalFailureException(Product.class,productID);
		}else{
			return product;
		}
	}

	@Override
	public Product save(Product product) {
		// TODO Auto-generated method stub
		getHibernateTemplate().saveOrUpdate(product);
		getHibernateTemplate().flush();
		return product;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getHot() {
		// TODO Auto-generated method stub
		List<Product> list=getHibernateTemplate().find("from Product order by hit");
		if(list.isEmpty()){
			return null;
		}else{
			return list;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getNew() {
		DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		Calendar fromCal=Calendar.getInstance();
		fromCal.setTime(new java.util.Date());
		fromCal.add(Calendar.DATE, -3);
		Date newDate=Date.valueOf(dateFormat.format(fromCal.getTime()));		
		List<Product> list=getHibernateTemplate().find("from Product where pubdate>=?",newDate);
		if(list.isEmpty()){
			return null;
		}else{
			return list;
		}
	}

}
